<?php

namespace App\Http\Controllers\Api\Merchant;

use App\Classify;
use App\DiscountSalesRule;
use App\DiscountXMedicine;
use App\Excels;
use App\Files;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Imports\MedicineImport;
use App\Imports\MedicineNewImport;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantMedicineApply;
use App\MerchantMedicineImg;
use App\MerchantMedicineSku;
use App\MerchantMedicineSkuValue;
use App\MerchantMedicineSpu;
use App\MerchantMedicineXClassify;
use App\MerchantStaff;
use App\Sku;
use App\SkuValue;
use App\SystemMedicine;
use App\SystemMedicineImg;
use App\SystemMedicineSku;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use Maatwebsite\Excel\Facades\Excel;
use function GuzzleHttp\Psr7\str;
use Storage;

class GoodsController extends Controller
{
    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $merchantId = $request->get('merchant_id') ?? 0;
        $isShop     = $request->get('is_shop') ?? '';
        $classifyId = $request->get('classify_id');
        $keyword    = $request->get('keyword') ?? '';

        if($MerchantUser->role == 3){
            $merchantStaff = MerchantStaff::whereUserId($MerchantUser->id)->first();
            if($merchantStaff){
                $merchantId = $merchantStaff->merchant_id;
            }
        }

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var MerchantMedicine $goodsList */
        $goodsList = MerchantMedicine::whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);

        if($merchantId != 0){
            $goodsList = $goodsList->whereMerchantId($merchantId);
        }

        if($keyword != ''){
            $goodsList = $goodsList->where('upc','like','%'.trim($keyword).'%')->orWhere('name','like','%'.trim($keyword).'%');
        }

        if($isShop !== ''){
            $goodsList = $goodsList->whereIsShop($isShop);
        }

        if($merchantId != 0){
            $goodsList = $goodsList->whereMerchantId($merchantId);
        }

        if(is_numeric($classifyId)){
            if($classifyId == 0){
                $classifyIds = Classify::whereEnterpriseId($enterpriseInfo->id)->pluck('id')->toArray();

                $merchantMedicineIds = MerchantMedicineXClassify::whereIn('classify_id',$classifyIds)->pluck('merchant_medicine_id')->toArray();

                $goodsList = $goodsList->whereNotIn('id',$merchantMedicineIds);
            }else{
                $merchantMedicineIds = MerchantMedicineXClassify::whereClassifyId($classifyId)->pluck('merchant_medicine_id')->toArray();

                $goodsList = $goodsList->whereIn('id',$merchantMedicineIds);
            }
        }

        $goodsList = $goodsList->whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);

        $pageInfo['total'] = $goodsList->count();

        $goodsList = $goodsList->orderBy('sort')->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($goodsList) > 0){
            foreach ($goodsList as $goods) {
                $goods->thumb_url = MerchantMedicine::getMerchantMedicineImg($goods->id);

                $goods->goods_type_name = MerchantMedicine::getGoodsTypeName($goods->goods_type);

                if($goods->is_shop == 1){
                    $goods->is_shop_name = '上架';
                }else{
                    $goods->is_shop_name = '下架';
                }

                $classifyIdArr = [];
                $classifyNameArr = [];
                $classifyList = MerchantMedicineXClassify::whereMerchantMedicineId($goods->id)->get();
                if (count($classifyList) > 0) {
                    foreach ($classifyList as $classify) {
                        $classifyName = Classify::getClassifyName($classify->classify_id);

                        array_push($classifyIdArr, $classify->classify_id);
                        array_push($classifyNameArr, $classifyName);
                    }
                }

                $goods->classify_list = $classifyIdArr;
                $goods->classify_name_list = $classifyNameArr;

                //商品链接
                $goods->link_url = '';

                $classifyNameArr = '';
                $classifyList = MerchantMedicineXClassify::whereMerchantMedicineId($goods->id)->get();
                if (count($classifyList) > 0) {
                    foreach ($classifyList as $classify) {
                        $classifyName = Classify::getClassifyName($classify->classify_id);

                        if($classifyName){
                            if($classifyNameArr){
                                $classifyNameArr .= ' - ' . $classifyName;
                            }else{
                                $classifyNameArr = $classifyName;
                            }
                        }
                    }
                }

                $goods->classify_name = $classifyNameArr;

                $goods->merchant_name = Merchant::getMerchantName($goods->merchant_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsList,'page_info' => $pageInfo,'data2' => $enterpriseInfo]);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsDetail(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goods = MerchantMedicine::whereId($id)->first();
        if($goods) {
            $goods->thumb_url = MerchantMedicine::getMerchantMedicineImgList($goods->id);

            $goods->goods_type_name = MerchantMedicine::getGoodsTypeName($goods->goods_type);

            $goods->classify_name = Classify::getClassifyName($goods->classify_id);

            $goods->merchant_name = Merchant::getMerchantName($goods->merchant_id);

            $classifyIdArr = [];
            $classifyNameArr = [];
            $classifyList = MerchantMedicineXClassify::whereMerchantMedicineId($goods->id)->get();
            if (count($classifyList) > 0) {
                foreach ($classifyList as $classify) {
                    $classifyName = Classify::getClassifyName($classify->classify_id);

                    array_push($classifyIdArr, $classify->classify_id);
                    array_push($classifyNameArr, $classifyName);
                }
            }

            $goods->classify_list = $classifyIdArr;
            $goods->classify_name_list = $classifyNameArr;

            $goods->all_sku_list = [];
            $sysGoods = SystemMedicine::whereUpc($goods->upc)->first();
            if($sysGoods) {
                $systemMedicineSkuIds = SystemMedicineSku::whereSystemMedicineId($sysGoods->id)->pluck('sku_id')->toArray();

                $skuList = Sku::whereStatus(1)->whereIn('id',$systemMedicineSkuIds)->orderBy('sort')->orderByDesc('created_at')->get();
                if(count($skuList) > 0){
                    foreach ($skuList as $skuL) {
                        $skuValueList = SkuValue::whereStatus(1)->whereSkuId($skuL->id)->orderBy('sort')->orderByDesc('created_at')->get();

                        $skuL->value_list = $skuValueList;
                    }
                }

                $goods->all_sku_list = $skuList;
            }

            $goods->sku_list = MerchantMedicine::getMerchantMedicineSku($goods->id);

            $goodsSkuList = MerchantMedicineSku::whereMerchantMedicineId($goods->id)->get();
            if (count($goodsSkuList) > 0) {
                foreach ($goodsSkuList as $goodsSku) {
                    $goodsSkuInfo = json_decode($goodsSku->specification_attr, true);

                    $skuInfo = [];
//                    if (count($goodsSkuArr) > 0){
//                        foreach ($goodsSkuArr as $val) {
                            if(count($goodsSkuInfo) > 0){
                                foreach ($goodsSkuInfo as $item) {
                                    $skuValueId = array_values((array)$item);
                                    $skuValue = SkuValue::whereId($skuValueId[0])->first();
                                    if($skuValue){
                                        array_push($skuInfo,$skuValue);
                                    }
                                }
                            }

//                        }
//                    }

                    $goodsSku->sku_info = $skuInfo;

                    $goodsSku->img_url = FileManager::getImgUrl($goodsSku->img_id);
                }
            }

            $goods->goods_sku_table = $goodsSkuList;

            $goods->discount_sales_rule_list = MerchantMedicine::getDiscountSalesRule($goods->id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goods]);
    }

    /**
     * 获取商品分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsClassify(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $merchantId = $request->get('merchant_id',0);

        $goodsClassifyList = Classify::wherePid(0);

        if(is_numeric($merchantId) && $merchantId != 0){
            $goodsClassifyList->whereMerchantId($merchantId);
        }

        $goodsClassifyList = $goodsClassifyList->whereType('selling')->orderBy('sort')->orderByDesc('created_at')->get();
        if(count($goodsClassifyList) > 0){
            foreach ($goodsClassifyList as $goodsClassify) {
                $goodsClassify->img_url = FileManager::getImgUrl($goodsClassify->img_id);
                $childList = Classify::wherePid($goodsClassify->id)->whereMerchantId($merchantId)->whereType('selling')->orderBy('sort')->orderByDesc('created_at')->get();
                if(count($childList) > 0){
                    foreach ($childList as $child) {
                        $child->img_url = FileManager::getImgUrl($child->img_id);
                    }
                }

                $goodsClassify->child_list = $childList;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsClassifyList]);
    }

    /**
     * 通过upc码获取商品库信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSystemMedicineByUpc(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $upc = $request->get('upc');

        $goods = SystemMedicine::whereUpc($upc)->first();
        if($goods) {
            $goods->thumb_url = SystemMedicine::getSystemMedicineImgList($goods->id);

            $systemMedicineSkuIds = SystemMedicineSku::whereSystemMedicineId($goods->id)->pluck('sku_id')->toArray();

            $skuList = Sku::whereStatus(1)->whereIn('id',$systemMedicineSkuIds)->orderBy('sort')->orderByDesc('created_at')->get();
            if(count($skuList) > 0){
                foreach ($skuList as $skuL) {
                    $skuValueList = SkuValue::whereStatus(1)->whereSkuId($skuL->id)->orderBy('sort')->orderByDesc('created_at')->get();

                    $skuL->value_list = $skuValueList;
                }
            }

            $goods->sku_list = $skuList;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goods]);
    }

    /**
     * 获取所有的upc码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSystemMedicineUpcList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $upc        = $request->get('upc') ?? '';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        $systemMedicineUpcList = SystemMedicine::whereStatus(1);

        if($upc != ''){
            $systemMedicineUpcList->where('upc','like','%'.trim($upc).'%');
        }

        $pageInfo['total'] = $systemMedicineUpcList->count();

        $systemMedicineUpcList = $systemMedicineUpcList->orderByDesc('id')->offset($limit * ($page - 1))->limit($limit)->pluck('upc')->toArray();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $systemMedicineUpcList,'page_info' => $pageInfo]);
    }

    /**
     * 查看是否已添加过该商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectGoodsExists(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $upc        = $request->get('upc') ?? '';
        $merchantId = $request->get('merchant_id') ?? 0;

        $data    = 0;
        $merchantMedicineApplyIsExists = MerchantMedicine::whereMerchantId($merchantId)->whereUpc($upc)->first();
        if($merchantMedicineApplyIsExists){
            $data = 1;
        }

        return response()->json(['level' => 'success','message' => '获取岑巩','data' => $data]);

    }

    /**
     * 编辑商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoods(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $upc                                 = $request->get('upc') ?? '';
        $ssn                                 = $request->get('ssn') ?? '';
        $name                                = $request->get('name') ?? '';
        $classifyId                          = $request->get('classify_id') ?? 0;
        $typeId                              = $request->get('type_id') ?? 0;
        $merchantId                          = $request->get('merchant_id') ?? 0;
        $skuSsn                              = $request->get('sku_ssn') ?? '';
        $approvalNumber                      = $request->get('approval_number') ?? '';
        $specification                       = $request->get('specification') ?? '';
        $thumbId                             = $request->get('thumb_id') ?? 0;
        $sellingPrice                        = $request->get('selling_price') ?? 0;
        $stock                               = $request->get('stock') ?? 0;
        $manufacturer                        = $request->get('manufacturer') ?? '';
        $manufacturerAddress                 = $request->get('manufacturer_address') ?? '';
        $manufacturerContact                 = $request->get('manufacturer_contact') ?? '';
        $electronicRegulatoryCode            = $request->get('electronic_regulatory_code') ?? '';
        $usageAndDosage                      = $request->get('usage_and_dosage') ?? '';
        $indications                         = $request->get('indications') ?? '';
        $adaptToTheCrowd                     = $request->get('adapt_to_the_crowd') ?? '';
        $component                           = $request->get('component') ?? '';
        $adverseReactions                    = $request->get('adverse_reactions') ?? '';
        $contraindications                   = $request->get('contraindications') ?? '';
        $precautions                         = $request->get('precautions') ?? '';
        $interaction                         = $request->get('interaction') ?? '';
        $medicationForChildren               = $request->get('medication_for_children') ?? '';
        $medicationForPregnancyXLactation    = $request->get('medication_for_pregnancy_x_lactation') ?? '';
        $medicationForAged                   = $request->get('medication_for_aged') ?? '';
        $properties                          = $request->get('properties') ?? '';
        $packing                             = $request->get('packing') ?? '';
        $dosageForm                          = $request->get('dosage_form') ?? '';
        $storage                             = $request->get('storage') ?? '';
        $pharmacologicalAction               = $request->get('pharmacological_action') ?? '';
        $expiryDate                          = $request->get('expiry_date') ?? '';
        $detail                              = $request->get('detail') ?? '';
        $isShop                              = $request->get('is_shop') ?? 0;
        $sort                                = $request->get('sort') ?? 0;
        $skuValueArr                         = $request->get('sku_value_arr');
        $skuVInfoArr                         = $request->get('sku_info_arr');
        $discountSalesRule                   = $request->get('discount_sales_rule');
        $id                                  = $request->get('id') ?? 0;

//        $systemMedicine = SystemMedicine::whereUpc($upc)->first();
//        if(!$systemMedicine){
//            $merchantMedicineApplyIsExists = MerchantMedicineApply::whereUpc($upc)->whereReview(0)->first();
//            if($merchantMedicineApplyIsExists)
//                return response()->json(['level' => 'error','message' => 'upc码重复']);
//
//            $merchantMedicineApply = new MerchantMedicineApply();
//            $merchantMedicineApply->upc                                   = $upc;
//            $merchantMedicineApply->name                                  = $name;
//            $merchantMedicineApply->enterprise_id                         = $enterpriseInfo->id;
//            $merchantMedicineApply->merchant_id                           = $merchantId;
//            $merchantMedicineApply->thumb_id                              = json_encode($thumbId);
//            $merchantMedicineApply->drug_type                             = $typeId;
//            $merchantMedicineApply->sku_ssn                               = $skuSsn;
//            $merchantMedicineApply->approval_number                       = $approvalNumber;
//            $merchantMedicineApply->specification                         = $specification;
//            $merchantMedicineApply->selling_price                         = $sellingPrice;
//            $merchantMedicineApply->stock                                 = $stock;
//            $merchantMedicineApply->manufacturer                          = $manufacturer;
//            $merchantMedicineApply->manufacturer_address                  = $manufacturerAddress;
//            $merchantMedicineApply->manufacturer_contact                  = $manufacturerContact;
//            $merchantMedicineApply->electronic_regulatory_code            = $electronicRegulatoryCode;
//            $merchantMedicineApply->usage_and_dosage                      = $usageAndDosage;
//            $merchantMedicineApply->indications                           = $indications;
//            $merchantMedicineApply->adapt_to_the_crowd                    = $adaptToTheCrowd;
//            $merchantMedicineApply->component                             = $component;
//            $merchantMedicineApply->adverse_reactions                     = $adverseReactions;
//            $merchantMedicineApply->contraindications                     = $contraindications;
//            $merchantMedicineApply->precautions                           = $precautions;
//            $merchantMedicineApply->interaction                           = $interaction;
//            $merchantMedicineApply->medication_for_children               = $medicationForChildren;
//            $merchantMedicineApply->medication_for_pregnancy_x_lactation  = $medicationForPregnancyXLactation;
//            $merchantMedicineApply->medication_for_aged                   = $medicationForAged;
//            $merchantMedicineApply->properties                            = $properties;
//            $merchantMedicineApply->packing                               = $packing;
//            $merchantMedicineApply->dosage_form                           = $dosageForm;
//            $merchantMedicineApply->storage                               = $storage;
//            $merchantMedicineApply->pharmacological_action                = $pharmacologicalAction;
//            $merchantMedicineApply->expiry_date                           = $expiryDate;
//            $merchantMedicineApply->detail                                = $detail;
//            $merchantMedicineApply->save();
//
//            return response()->json(['level' => 'success','message' => '提交成功,请等待审核','data' => $merchantMedicineApply]);
//        }else{
            $merchant = Merchant::whereId($merchantId)->first();
            if(!$merchant)
                return response()->json(['level' => 'error','message' => '门店不存在']);

            $merchantMedicine = MerchantMedicine::whereId($id)->first();
            if(!$merchantMedicine)
                $merchantMedicine = new MerchantMedicine();

            if(!empty($upc))
                 $merchantMedicine->upc                                   = $upc;
            if(!empty($ssn))
                $merchantMedicine->ssn                                   = $ssn;
            if(!empty($name))
                $merchantMedicine->name                                  = $name;
            if(!empty($merchantId))
                $merchantMedicine->merchant_id                           = $merchantId;
            if(!empty($typeId))
                $merchantMedicine->drug_type                             = $typeId;
//            $merchantMedicine->thumb_id                              = $thumbId;
            if(!empty($skuSsn))
                $merchantMedicine->sku_ssn                               = $skuSsn;
            if(!empty($approvalNumber))
                $merchantMedicine->approval_number                       = $approvalNumber;
            if(!empty($specification))
                $merchantMedicine->specification                         = $specification;
            if(!is_null($sellingPrice) && $sellingPrice !== '')
                $merchantMedicine->selling_price                         = $sellingPrice;
            if(!empty($stock) || is_numeric($stock))
                $merchantMedicine->stock                                 = $stock;
            if(!empty($manufacturer))
                $merchantMedicine->manufacturer                          = $manufacturer;
            if(!empty($manufacturerAddress))
                $merchantMedicine->manufacturer_address                  = $manufacturerAddress;
            if(!empty($manufacturerContact))
                $merchantMedicine->manufacturer_contact                  = $manufacturerContact;
            if(!empty($electronicRegulatoryCode))
                $merchantMedicine->electronic_regulatory_code            = $electronicRegulatoryCode;
            if(!empty($usageAndDosage))
                $merchantMedicine->usage_and_dosage                      = $usageAndDosage;
            if(!empty($indications))
                $merchantMedicine->indications                           = $indications;
            if(!empty($adaptToTheCrowd))
                $merchantMedicine->adapt_to_the_crowd                    = $adaptToTheCrowd;
            if(!empty($component))
                $merchantMedicine->component                             = $component;
            if(!empty($adverseReactions))
                $merchantMedicine->adverse_reactions                     = $adverseReactions;
            if(!empty($contraindications))
                $merchantMedicine->contraindications                     = $contraindications;
            if(!empty($precautions))
                $merchantMedicine->precautions                           = $precautions;
            if(!empty($interaction))
                $merchantMedicine->interaction                           = $interaction;
            if(!empty($medicationForChildren))
                $merchantMedicine->medication_for_children               = $medicationForChildren;
            if(!empty($medicationForPregnancyXLactation))
                $merchantMedicine->medication_for_pregnancy_x_lactation  = $medicationForPregnancyXLactation;
            if(!empty($medicationForAged))
                $merchantMedicine->medication_for_aged                   = $medicationForAged;
            if(!empty($properties))
                $merchantMedicine->properties                            = $properties;
            if(!empty($packing))
                $merchantMedicine->packing                               = $packing;
            if(!empty($dosageForm))
                $merchantMedicine->dosage_form                           = $dosageForm;
            if(!empty($storage))
                $merchantMedicine->storage                               = $storage;
            if(!empty($pharmacologicalAction))
                $merchantMedicine->pharmacological_action                = $pharmacologicalAction;
            if(!empty($expiryDate))
                $merchantMedicine->expiry_date                           = $expiryDate;
            if(!empty($detail))
                $merchantMedicine->detail                                = $detail;
            if(!empty($isShop))
                $merchantMedicine->is_shop                               = $isShop;
            if(!empty($sort))
                $merchantMedicine->sort                                  = $sort;
            $merchantMedicine->save();

            if(is_array($thumbId)){
                $merchantMedicineImgList = MerchantMedicineImg::whereMerchantMedicineId($merchantMedicine->id)->get();
                if(count($merchantMedicineImgList) > 0){
                    foreach ($merchantMedicineImgList as $merchantMedicineImg) {
                        $merchantMedicineImg->delete();
                    }
                }

                if(count($thumbId) > 0){
                    foreach ($thumbId as $img) {
                        $newMerchantMedicineImg = new MerchantMedicineImg();
                        $newMerchantMedicineImg->merchant_medicine_id = $merchantMedicine->id;
                        $newMerchantMedicineImg->img_id               = $img;
                        $newMerchantMedicineImg->save();
                    }
                }
            }

            if(is_array($classifyId) && count($classifyId) > 0){
                $merchantMedicineXClassify = MerchantMedicineXClassify::whereMerchantMedicineId($merchantMedicine->id)->get();
                if(count($merchantMedicineXClassify) > 0){
                    foreach ($merchantMedicineXClassify as $item) {
                        $item->delete();
                    }
                }

                foreach ($classifyId as $val){
                    $merchantMedicineXClassify = new MerchantMedicineXClassify();
                    $merchantMedicineXClassify->classify_id            = $val;
                    $merchantMedicineXClassify->merchant_medicine_id   = $merchantMedicine->id;
                    $merchantMedicineXClassify->save();
                }
            }

            if(is_array($discountSalesRule) && count($discountSalesRule) > 0){
                self::setDiscountSalesXMedicineToMedicineIde($discountSalesRule,$merchantMedicine->id,$merchant->id);
            }

            if(is_array($skuValueArr) && count($skuValueArr) > 0){
                $skuValueList = MerchantMedicineSkuValue::whereEnterpriseId($enterpriseInfo->id)->whereMerchantMedicineId($merchantMedicine->id)->get();
                if(count($skuValueList)){
                    foreach ($skuValueList as $skuValue) {
                        $skuValue->delete();
                    }
                }

                foreach ($skuValueArr as $value) {
                    if(count($value['sku_value_id']) > 0){
                        foreach ($value['sku_value_id'] as $item){
                            $newSkuValue = new MerchantMedicineSkuValue();
                            $newSkuValue->enterprise_id        = $enterpriseInfo->id;
                            $newSkuValue->merchant_medicine_id = $merchantMedicine->id;
                            $newSkuValue->sku_id               = $value['sku_id'];
                            $newSkuValue->sku_value_id         = $item;
                            $newSkuValue->save();
                        }
                    }
                }
            }

            if(is_array($skuVInfoArr) && count($skuVInfoArr) > 0){
                $goodsSkuList= MerchantMedicineSku::whereEnterpriseId($enterpriseInfo->id)->whereMerchantMedicineId($merchantMedicine->id)->get();
                if(count($goodsSkuList) > 0){
                    foreach ($goodsSkuList as $goodsSku) {
                        $goodsSku->delete();
                    }
                }

                foreach($skuVInfoArr as $skuVInfo){
                    $newGoodsSku = new MerchantMedicineSku();
                    $newGoodsSku->enterprise_id              = $enterpriseInfo->id;
                    $newGoodsSku->merchant_medicine_id       = $merchantMedicine->id;
                    $newGoodsSku->specification_attr         = json_encode($skuVInfo[0]);
                    $newGoodsSku->img_id                     = $skuVInfo[1] ? $skuVInfo[1] : 0;
                    $newGoodsSku->price                      = $skuVInfo[2] ? $skuVInfo[2] : 0;
                    $newGoodsSku->stock                      = $skuVInfo[3] ? $skuVInfo[3] : 0;
                    $newGoodsSku->sku_num                    = $skuVInfo[4] ? $skuVInfo[4] : '';
                    $newGoodsSku->status                     = 1;
                    $newGoodsSku->save();
                }
            }

            return response()->json(['level' => 'success','message' => '设置成功','data' => $merchantMedicine]);
//        }
    }

    /**
     * 获取商品规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsSkuList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $upc            = $request->get('upc') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $systemMedicineSkuIds = [];
        $systemMedicine = SystemMedicine::whereUpc($upc)->first();
        if($systemMedicine){
            $systemMedicineSkuIds = SystemMedicineSku::whereSystemMedicineId($systemMedicine->id)->pluck('sku_id')->toArray();
        }

        $skuList = Sku::whereStatus(1)->whereIn('id',$systemMedicineSkuIds)->orderBy('sort')->orderByDesc('created_at')->get();
        if(count($skuList) > 0){
            foreach ($skuList as $skuL) {
                $skuValueList = SkuValue::whereStatus(1)->whereSkuId($skuL->id)->orderBy('sort')->orderByDesc('created_at')->get();

                $skuL->value_list = $skuValueList;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $skuList,'page_info' => $pageInfo]);
    }

    /**
     * 删除商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGoods(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $merchantMedicine = MerchantMedicine::whereId($id)->first();
        if(!$merchantMedicine)
            return response()->json(['level' => 'error','message' => '该药品不存在']);

        $merchantMedicine->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $merchantMedicine]);
    }

    /**
     * 改变上下架状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeGoodsShop(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $merchantMedicine = MerchantMedicine::whereId($id)->first();
        if(!$merchantMedicine)
            return response()->json(['level' => 'error','message' => '该药品不存在']);

        if($merchantMedicine->is_shop == 1){
            $merchantMedicine->is_shop = 0;
        }else{
            $merchantMedicine->is_shop = 1;
        }

        $merchantMedicine->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $merchantMedicine]);
    }

    /**
     * 商品规格列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsSpuList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('merchant_medicine_id') ?? 0;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $MerchantMedicineSpuList = MerchantMedicineSpu::whereMerchantMedicineId($id);

        $pageInfo['total'] = $MerchantMedicineSpuList->count();

        $MerchantMedicineSpuList = $MerchantMedicineSpuList->orderBy('sort')->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($MerchantMedicineSpuList) > 0){
            foreach ($MerchantMedicineSpuList as $MerchantMedicineSpu) {
                if($MerchantMedicineSpu->status == 1){
                    $MerchantMedicineSpu->status_name = '开启';
                }else{
                    $MerchantMedicineSpu->status_name = '关闭';
                }

                $MerchantMedicineSpu->merchant_medicine_name = '';

                $merchantMedicine = MerchantMedicine::whereId($MerchantMedicineSpu->merchant_medicine_id)->first();
                if($merchantMedicine){
                    $MerchantMedicineSpu->merchant_medicine_name = $merchantMedicine->name;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $MerchantMedicineSpuList,'page_info' => $pageInfo]);
    }

    /**
     * 商品规格详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsSpuDetail(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $merchantMedicineSpu = MerchantMedicineSpu::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $merchantMedicineSpu]);
    }

    /**
     * 设置商品规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoodsSpu(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $merchantMedicineId = $request->get('merchant_medicine_id') ?? 0;
        $spuName            = $request->get('spu_name') ?? '';
        $specification      = $request->get('specification') ?? '';
        $price              = $request->get('price') ?? 0;
        $stock              = $request->get('stock') ?? 0;
        $sort               = $request->get('sort') ?? 0;
        $status             = $request->get('status') ?? 0;
        $id                 = $request->get('id') ?? 0;

        $newMerchantMedicine = MerchantMedicineSpu::whereId($id)->first();
        if(!$newMerchantMedicine)
            $newMerchantMedicine = new MerchantMedicineSpu();

        $newMerchantMedicine->merchant_medicine_id = $merchantMedicineId;
        $newMerchantMedicine->spu_name             = $spuName;
        $newMerchantMedicine->specification        = $specification;
        $newMerchantMedicine->price                = $price;
        $newMerchantMedicine->stock                = $stock;
        $newMerchantMedicine->sort                 = $sort;
        $newMerchantMedicine->status               = $status;
        $newMerchantMedicine->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newMerchantMedicine]);
    }

    public function getDiscountSalesRule(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $page=$page-1;

        $pageInfo['total']=DiscountSalesRule::whereEnterpriseId($enterpriseInfo->id)->count();
        $rules=DiscountSalesRule::whereEnterpriseId($enterpriseInfo->id)->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($rules) > 0){
            /** @var DiscountSalesRule $item */
            foreach ($rules as $item){
                $item->merchant_name=Merchant::getMerchantName($item->merchant_id);
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$rules,'page_info'=>$pageInfo]);

    }
    /**
     * 设置促销规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDiscountSalesRule(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $name           =$request->get('name');
        $type='reduce';
//        $type=$request->get('type');
//        $range=$request->get('range');
//        $satisfy_number=$request->get('satisfy_number');
        $satisfy_money  =$request->get('satisfy_amount');
        $free_get_number=$request->get('free_get_number');
        $reduce_amount  =$request->get('reduce_amount');
        $reduce_rate    =$request->get('reduce_rate');
        $start_time     =$request->get('start_time');
        $end_time       =$request->get('end_time');
        $status         =$request->get('status');
        $id             =$request->get('id');

        if (!$name)
            return response()->json(["level"=>"error","message"=>"请输入规则名称"]);

        if (!in_array($type,['buy_get_free','reduce','discount']))
            return response()->json(["level"=>"error","message"=>"请选择规则类型"]);
//        if (!in_array($range,['vip','all']))
//            return response()->json(["level"=>"error","message"=>"请选择适用范围"]);

//        if (!is_numeric($satisfy_number))
//            return response()->json(["level"=>"error","message"=>"请输入满足条件的数量"]);
//        if ($satisfy_number < 1)
//            return response()->json(["level"=>"error","message"=>"满的数量需要大于等于1"]);

        if ($type == 'buy_get_free'){
            if (!is_numeric($free_get_number))
                return response()->json(["level"=>"error","message"=>"请输入赠送的数量"]);
        }

        if ($type == 'reduce'){
            if (!is_numeric($reduce_amount))
                return response()->json(["level"=>"error","message"=>"请输入减掉的金额"]);
        }
        if ($type == 'discount'){
            if (!is_numeric($reduce_rate))
                return response()->json(["level"=>"error","message"=>"请输入优惠的折扣率"]);
            if ($reduce_rate<=0 || $reduce_rate > 1)
                return response()->json(["level"=>"error","message"=>"取值范围是大于0，且小于等于1"]);
        }
        $thisRule=DiscountSalesRule::whereId($id)->first();
        if (!$thisRule)
            $thisRule=new DiscountSalesRule();
        $thisRule->name=$name;
        $thisRule->type=$type;
        $thisRule->enterprise_id=$enterpriseInfo->id;
//        $thisRule->range=$range;
//        $thisRule->satisfy_number   =$satisfy_number;
        $thisRule->satisfy_amount   =$satisfy_money ?? 0;
        $thisRule->status           =$status ? 1 : 0;

        if ($start_time)
            $thisRule->start_time   =$start_time;
        if ($end_time)
            $thisRule->end_time     =$end_time;
        if ($type == 'buy_get_free')
            $thisRule->free_get_number=$free_get_number;
        if ($type == 'reduce')
            $thisRule->reduce_amount=$reduce_amount;
        if ($type == 'discount')
            $thisRule->reduce_rate  =$reduce_rate;
        $thisRule->save();

        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    /**
     * 修改促销规则状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeDiscountSalesRuleStatus(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id             =$request->get('id');

        $thisRule = DiscountSalesRule::whereId($id)->first();
        if(!$thisRule)
            return response()->json(['level' => 'error','message' => '该规则不存在']);

        if($thisRule->status == 1){
            $thisRule->status = 0;
        }else{
            $thisRule->status = 1;
        }

        $thisRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisRule]);
    }

    /**
     * 药品绑定促销规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function setDiscountSalesXMedicine(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $discount_sales_rule_ids   = $request->get('discount_sales_rule_ids');
        $medicine_id  = $request->get('medicine_id');

        $exist_rules_ids    =DiscountXMedicine::whereMerchantMedicineId($medicine_id)->pluck('discount_sales_rule_id')->toArray();
        $add_rules_ids      =array_diff($discount_sales_rule_ids,$exist_rules_ids);
        $delete_rules_ids   =array_diff($exist_rules_ids,$discount_sales_rule_ids);
        if (count($add_rules_ids) > 0){
            foreach ($add_rules_ids as $add_rules_id){
                $rule=DiscountSalesRule::whereId($add_rules_id)->first();
                if ($rule){
                    $exist=DiscountXMedicine::whereMerchantMedicineId($medicine_id)->whereDiscountSalesRuleId($add_rules_id)->first();
                    if (!$exist){
                        $newGoodsRule=new DiscountXMedicine();
                        $newGoodsRule->discount_sales_rule_id=$add_rules_id;
                        $newGoodsRule->merchant_id=$medicine_id;
                        $newGoodsRule->save();
                    }
                }
            }
        }

        if (count($delete_rules_ids) > 0){
            DiscountXMedicine::whereMerchantMedicineId($medicine_id)->whereIn('discount_sales_rule_id',$delete_rules_ids)->delete();
        }
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    public static function setDiscountSalesXMedicineToMedicineIde($discount_sales_rule_ids = [],$medicine_id = 0,$merchantId = 0){
        $exist_rules_ids    =DiscountXMedicine::whereMerchantMedicineId($medicine_id)->pluck('discount_sales_rule_id')->toArray();
        $add_rules_ids      =array_diff($discount_sales_rule_ids,$exist_rules_ids);
        $delete_rules_ids   =array_diff($exist_rules_ids,$discount_sales_rule_ids);
        if (count($add_rules_ids) > 0){
            foreach ($add_rules_ids as $add_rules_id){
                $rule=DiscountSalesRule::whereId($add_rules_id)->first();
                if ($rule){
                    $exist=DiscountXMedicine::whereMerchantMedicineId($medicine_id)->whereDiscountSalesRuleId($add_rules_id)->first();
                    if (!$exist){
                        $newGoodsRule=new DiscountXMedicine();
                        $newGoodsRule->discount_sales_rule_id=$add_rules_id;
                        $newGoodsRule->merchant_id=$merchantId;
                        $newGoodsRule->merchant_medicine_id = $medicine_id;
                        $newGoodsRule->save();
                    }
                }
            }
        }

        if (count($delete_rules_ids) > 0){
            DiscountXMedicine::whereMerchantMedicineId($medicine_id)->whereIn('discount_sales_rule_id',$delete_rules_ids)->delete();
        }

        return true;
    }
    /**
     * 删除促销规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delDiscountSalesRule(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id');
        $thisRule=DiscountSalesRule::whereId($id)->first();
        if (!$thisRule)
            return response()->json(['level'=>'error','message'=>'该记录不存在']);
        $thisRule->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    /**
     * 删除商品规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGoodsSpu(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $newMerchantMedicine = MerchantMedicineSpu::whereId($id)->first();
        if(!$newMerchantMedicine)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $newMerchantMedicine->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $newMerchantMedicine]);
    }

    /**
     * 商品审核列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsApplyList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $review     = $request->get('review') ?? '';


        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var MerchantMedicineApply $goods */
        $goodsApplyList = MerchantMedicineApply::whereNull('deleted_at');

        if($review !== ''){
            $goodsApplyList = $goodsApplyList->whereReview($review);
        }

        $pageInfo['total'] = $goodsApplyList->count();

        $goodsApplyList = $goodsApplyList->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($goodsApplyList) > 0){
            foreach ($goodsApplyList as $goods) {
                $imgUrl = '';
                if($goods->thumb_id){
                    $goodsImgList = json_decode($goods->thumb_id,true);
                    if(count($goodsImgList) > 0){
                        $imgUrl = FileManager::getImgUrl($goodsImgList[0]);
                    }
                }

                $goods->thumb_url = $imgUrl;

                if($goods->is_shop == 1){
                    $goods->is_shop_name = '上架';
                }else{
                    $goods->is_shop_name = '下架';
                }

                $goods->classify_name = Classify::getClassifyName($goods->classify_id);

                $goods->merchant_name = Merchant::getMerchantName($goods->merchant_id);

                if($goods->review == 1){
                    $goods->review_name = '通过';
                }elseif($goods->review == 2){
                    $goods->review_name = '拒绝';
                }else{
                    $goods->review_name = '待审核';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsApplyList,'page_info' => $pageInfo]);
    }

    /**
     *  获取审核商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsApplyDetail(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goodsApply = MerchantMedicineApply::whereId($id)->first();
        if($goodsApply){
            $goodsImgArr = [];
            if($goodsApply->thumb_id){
                $goodsImgList = json_decode($goodsApply->thumb_id,true);
                if(count($goodsImgList) > 0){
                    foreach ($goodsImgList as $goodsImg) {
                        $imgUrl = FileManager::getImgUrl($goodsImg);
                        array_push($goodsImgArr,$imgUrl);
                    }
                }
            }

            $goodsApply->thumb_url = $goodsImgArr;

            $goodsApply->merchant_name = Merchant::getDeliveryName($goodsApply->merchant_id);

            if($goodsApply->review == 1){
                $goodsApply->review_name = '通过';
            }elseif($goodsApply->review == 2){
                $goodsApply->review_name = '拒绝';
            }else{
                $goodsApply->review_name = '待审核';
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsApply]);
    }

    /**
     * 录入商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function importGoods(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $excelId = !is_null($request->get('excel_id')) ? $request->get('excel_id') : '';
        $type    = $request->input('type','retrieval');

        /** @var Excels $thatExcel */
        $thatExcel = Excels::whereId($excelId)->first();
        if(!$thatExcel)
            return response()->json(['level' => 'error','message' => '未找到文档']);

        /** @var Files $file */
        $file= Files::whereId($thatExcel->file_id)->first();
        if(!$file)
            return response()->json(['level' => 'error','message' => '文件不存在']);

        $excelUrl = $file->getLocalPath();

//        $fixedAssetsList = Excel::selectSheetsByIndex(0)->load($excelUrl,'UTF-8')->get();
        $import = new MedicineImport($enterpriseInfo->id,$type);
        $fixedAssetsList = Excel::import($import,$excelUrl);


        if($type == 'input'){
            return response()->json(['level' => 'success','message' => '录入成功','data' => $fixedAssetsList]);
        }else{
            $abnormalDataArr = $import->getbnormalData();
            if(!empty($abnormalDataArr)){
                return response()->json(['level' => 'error','message' => '出现异常数据','data' => $abnormalDataArr]);
            }else{
                return response()->json(['level' => 'success','message' => '无异常数据']);
            }
        }
    }

    public function importGoodsNew(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $excelId = !is_null($request->get('excel_id')) ? $request->get('excel_id') : '';
        $type    = $request->input('type','retrieval');

        /** @var Excels $thatExcel */
        $thatExcel = Excels::whereId($excelId)->first();
        if(!$thatExcel)
            return response()->json(['level' => 'error','message' => '未找到文档']);

        /** @var Files $file */
        $file= Files::whereId($thatExcel->file_id)->first();
        if(!$file)
            return response()->json(['level' => 'error','message' => '文件不存在']);

        $excelUrl = $file->getLocalPath();

//        $fixedAssetsList = Excel::selectSheetsByIndex(0)->load($excelUrl,'UTF-8')->get();
        $import = new MedicineNewImport($enterpriseInfo->id,$type);
        Excel::import($import,$excelUrl);

        if($type == 'input'){
            return response()->json(['level' => 'success','message' => '录入成功']);
        }else{
            $abnormalDataArr = $import->getbnormalData();
            if(!empty($abnormalDataArr)){
                return response()->json(['level' => 'error','message' => '出现异常数据','data' => $abnormalDataArr]);
            }else{
                return response()->json(['level' => 'success','message' => '无异常数据']);
            }
        }
    }

    public static function imgOss(){
        echo 'start_time'.PHP_EOL;
        $num = 0;
        $fileList = Files::whereDisk('local')->get();
        if(count($fileList) > 0){
            foreach ($fileList as $file) {
                $file->file_url = env('OSS_FILE_DIR') . '/' . $file->file_url;
                $file->disk     = 'oss';
                $file->save();
                $num++;
                echo '第' . $num . PHP_EOL;
            }
        }

        echo 'success';
    }

    public function getImgUrlInfo(Request $request){
        $imgId = $request->get('img_id',0);

        $imgUrl = FileManager::getImgUrl($imgId);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $imgUrl]);
    }
}
